<?php
require_once __DIR__ . '/../vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;

$config = [
    'host' => '127.0.0.1',
    'vhost' => '/',
    'port' => 5672,
    'login' => 'guest',
    'password' => 'guest',
];

//交换器名称
$exchange = 'routing';

try {
    //建立连接到RabbitMQ服务器
    $connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'], $config['vhost']);
    //建立通道
    $channel = $connection->channel();
    //声明一个交换机
    $channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, false, false);
    //声明一个队列
    list($queueName, ,) = $channel->queue_declare("", false, false, true, false);
    //获取routing_key
    $routingKeys = array_slice($argv, 1);
    //输入routing_key
    if (empty($routingKeys)) throw new Exception('请输入至少一个routing_key');
    foreach ($routingKeys as $routingKey) {
        // 队列通过routing_key绑定交换机
        $channel->queue_bind($queueName, $exchange, $routingKey);
    }
    echo " [*] Waiting for logs. To exit press CTRL+C\n";
    $callback = function ($msg) { // 回调函数
        sleep(3);
        // 手动确认消息是否正常消费，保证消息消费的幂等。
        $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        echo ' [x] Received ', $msg->delivery_info['routing_key'], ':', $msg->body, "\n";
    };
    $channel->basic_consume($queueName, '', false, false, false, false, $callback); // 消费消息
    while ($channel->is_consuming()) { // 循环消费消息，没有阻塞等待
        $channel->wait();
    }
    $channel->close(); // 通道关闭
    $connection->close(); // 连接关闭
} catch (Exception $e) {
    die($e->getMessage());
}